package open.tech.dawn.rest.module.system.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import open.tech.dawn.jdbc.SuperServiceImpl;
import open.tech.dawn.rest.module.system.entity.MenuNode;
import open.tech.dawn.rest.module.system.entity.ZTreeNode;
import open.tech.dawn.rest.module.system.mapper.SysMenuMapper;
import open.tech.dawn.rest.module.system.model.SysMenu;
import open.tech.dawn.rest.module.system.service.ISysMenuService;
import open.tech.dawn.web.util.ToolUtil;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * <p>
 * 菜单表 服务实现类
 * </p>
 *
 * @author joss
 * @since 2019-11-07
 */
@Service
public class SysMenuServiceImpl extends SuperServiceImpl<SysMenuMapper, SysMenu> implements ISysMenuService {

    @Override
    @Transactional
    public void delMenu(Long menuId) {

        //删除菜单
        baseMapper.deleteById(menuId);

        //删除关联的relation
        baseMapper.deleteRelationByMenu(menuId);
    }

    @Override
    @Transactional
    public void delMenuContainSubMenus(Long menuId) {

        SysMenu menu = baseMapper.selectById(menuId);

        //删除当前菜单
        delMenu(menuId);

        //删除所有子菜单
        QueryWrapper<SysMenu> wrapper = new QueryWrapper<>();
        wrapper = wrapper.like("pcodes", "%[" + menu.getCode() + "]%");
        List<SysMenu> menus = baseMapper.selectList(wrapper);
        for (SysMenu temp : menus) {
            delMenu(temp.getId());
        }
    }

    @Override
    public List<SysMenu> selectMenus(String condition, String level) {
        return this.baseMapper.selectMenus(condition, level);
    }

    @Override
    public List<Long> getMenuIdsByRoleId(Integer roleId) {
        return this.baseMapper.getMenuIdsByRoleId(roleId);
    }

    @Override
    public List<ZTreeNode> menuTreeList() {
        return this.baseMapper.menuTreeList();
    }

    @Override
    public List<ZTreeNode> menuTreeListByMenuIds(List<Long> menuIds) {
        return this.baseMapper.menuTreeListByMenuIds(menuIds);
    }

    @Override
    public int deleteRelationByMenu(Long menuId) {
        return this.baseMapper.deleteRelationByMenu(menuId);
    }

    @Override
    public List<String> getResUrlsByRoleId(Integer roleId) {
        return this.baseMapper.getResUrlsByRoleId(roleId);
    }

    @Override
    public List<MenuNode> getMenusByRoleIds(List<Integer> roleIds) {
        return this.baseMapper.getMenusByRoleIds(roleIds);
    }

    @Override
    public String getMenuNameByCode(String code) {
        if (ToolUtil.isEmpty(code)) {
            return "";
        } else {
            SysMenu param = new SysMenu();
            param.setCode(code);
            SysMenu menu = baseMapper.selectOne(new QueryWrapper<>(param));
            if (menu == null) {
                return "";
            } else {
                return menu.getName();
            }
        }
    }

}
